// 创建上下文菜单


// chrome.runtime.onStartup.addListener(() => {
// console.log('onStartup', arguments)

const contextMenus = [
  { id: "showResult", title: "刷题进度" }
];
for (let menu of contextMenus) {
  chrome.contextMenus.create({
    id: menu.id,
    type: "normal",
    title: menu.title,
    contexts: ["all"], // 右键点击选中文字时显示
    documentUrlPatterns: ["*://*.luogu.com.cn/*"], // 限制菜单选项仅应用于URL匹配给定模式之一的页面
  });
}
// })
function showNoLoginNotice () {

  chrome.notifications.create("notlogin11" + new Date().getTime(), {
    type: "basic",
    iconUrl: "../images/icon.png",
    title: "洛谷辅助插件提示",
    message: "洛谷未登录，请登录后尝试！"
  });

}

function notice (message) {
  chrome.notifications.create("notlogin11" + new Date().getTime(), {
    type: "basic",
    iconUrl: "../images/icon.png",
    title: "洛谷辅助插件提示",
    message: message
  })
}
// 监听上下文菜单点击事件
chrome.contextMenus.onClicked.addListener((info) => {
  console.log("info", info)
  if (info.pageUrl.indexOf('luogu.'))
    // if (info.selectionText) {
    switch (info.menuItemId) {
      case "showResult":
        refreshLuoguResult()
        //  chrome.windows.create({
        //   url: chrome.runtime.getURL("/html/result.html"),
        //   type: "popup",
        //   top: 10,
        //   left: 10,
        //   width: 800,
        //   height: 500,
        // });
        break;
      default:
        break;
    }
  // }
});
function refreshLuoguResult () {
  chrome.cookies.get({
    url: "https://www.luogu.com.cn",
    name: "_uid"
  }, function (cookie) {
    console.log('cookie is', cookie.value)
    if (!cookie.value || cookie.value == '0') {
      showNoLoginNotice()
      return
    }
    var key = "LuoguResult_" + cookie.value
    // chrome.tabs.create({
    //   url: chrome.runtime.getURL("/base/dist/index.html?uid="+ cookie.value) 
    // });

    // return
    chrome.storage.local.get(key, function (savedResult) {
      savedResult = savedResult ? savedResult[key] ? JSON.parse(savedResult[key]) : [] : []
      chrome.tabs.query({
        active: true,
        currentWindow: true
      }, (tabs) => {
        console.log(tabs)
        if (tabs.length == 0) {
          notice('浏览器异常')
        } else {
          chrome.tabs.sendMessage(tabs[0].id, {
            action: "getAllResult",
            uid: cookie.value,
            savedCount: savedResult.length,
            savedResult: savedResult
          }, (result) => {
            var item = {};
            console.log('result is ', JSON.stringify(result.records))
            savedResult = result.records.concat(savedResult)
            item[key] = JSON.stringify(savedResult)
            chrome.storage.local.set(item)
            jumpToView(cookie.value)
          })
        }

      })
    })

  })

}

chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
  if (request.action == "getCookie") {
    console.log('getCookie', chrome.cookies)
    chrome.cookies.getAll({ domain: request.domain }, function (cookies) {
      console.log('cookies', cookies)
      sendResponse({ cookies: cookies, request: request });
    });
  }
  else if (request.action == "getLuoguUID") {
    chrome.cookies.get({
      url: "https://www.luogu.com.cn",
      name: "_uid"
    }, function (cookie) {
      sendResponse({ uid: cookie.value });
    })
  }
  else if (request.action == "getLouguResult") {
    getSavedLuoguResult(request.uid, (result) => {
      sendResponse(result)
    })
  }
  else if (request.action == "clearLuoguResult") {
    clearLuoguResult(request.uid, (result) => {
      sendResponse(result)
    })
  } else if (request.action == "refreshLuoguResult") {
    refreshLuoguResult()
  } else if (request.action == "jumpToView") {
    if (request.uid) jumpToView(request.uid)
    else getUid().then(uid => jumpToView(uid))
  }
  return true;
});

function jumpToView (uid) {
  chrome.tabs.create({
    url: chrome.runtime.getURL("/website/dist/index.html?uid=" + uid)
  });
}

function clearLuoguResult (uid, callback) {
  const key = "LuoguResult_" + uid
  chrome.storage.local.remove(key, () => {
    callback(true)
  })
}

function getUid () {
  return new Promise((resolve, reject) => {
    chrome.cookies.get({
      url: "https://www.luogu.com.cn",
      name: "_uid"
    }, function (cookie) {
      if (!cookie.value || cookie.value == '0') {
        notice(NOLOGIN)
      } else {
        resolve(cookie.value)
      }
    })
  })
}
function getSavedLuoguResult (uid, callback) {
  var key = "LuoguResult_" + uid
  // chrome.tabs.create({
  //   url: chrome.runtime.getURL("/html/result.html?uid="+ cookie.value) 
  // });

  // return
  chrome.storage.local.get(key, function (savedResult) {
    savedResult = savedResult ? savedResult[key] ? JSON.parse(savedResult[key]) : [] : []
    callback(savedResult)

  })
}


// chrome.action.setBadgeBackgroundColor(
//   {color: [0, 255, 0, 0]},  // Green
//   () => { /* ... */ },
// );

// chrome.action.setBadgeText(
//   {
//     text: "new" 
//   },
//   () => {  }
// );

// 首次打开
chrome.runtime.onInstalled.addListener(async (_reason) => {
  // chrome.tabs.create({
  //   url: 'demo/index.html'
  // });
  console.log('onInstalled', _reason)
  //  chrome.action.setPopup({ popup: 'html/popup.html'}, (e) => {
  //   console.log(e)
  //  }) 
});

// 设置Popup
// await chrome.action.setPopup({ popup });
chrome.action.onClicked.addListener(async () => {
  console.log('this')
  let actionEnabled = await chrome.action.isEnabled();
  console.log('actionEnabled', actionEnabled)
  // when the button is clicked negate the state
  //  if (actionEnabled) {
  //    chrome.action.disable();
  //  } else {
  //    chrome.action.enable();
  //  }
  const popup = await chrome.action.getPopup({});
  await chrome.action.setPopup({ popup: 'html/popup.html' })
});






// chrome.tabs.onAttached.addListener(
//   (tabs) => {
//     console.log('onAttached', tabs)
//   },
// )


// chrome.tabs.onRemoved.addListener(
//   (tabs) => {
//     console.log('onRemoved', tabs)
//   },
// )
const TabItem = function (id, url, favIconUrl) {
  this.id = id
  this.url = url
  this.favIconUrl = favIconUrl
  this.title = ""
  this.starTime = new Date()
  this.endTime;
  this.timer;
  this.upload = () => {

  }
  this.request = (action) => {
    fetch(`http://localhost:18081/?tabId=${this.id}&action=${action}&t=${new Date().getTime()}&title=${encodeURIComponent(this.title)}&url=${encodeURIComponent(this.url)}&favIconUrl=${encodeURIComponent(this.favIconUrl)}`)
  }
  this.show = () => {
    this.request('show')
  }
  this.hide = () => {
    this.request('hide')
  }
  this.update = () => {
    console.log('update')
    chrome.tabs.get(this.id, (tabItem) => {
      // console.log("query", tabItem)
      if (tabItem.url != this.url) {
        this.url = tabItem.url
        this.title = tabItem.title
        this.request('update')

      }
    }
    )
  }
  this.dispose = () => {
    this.request('remove')

  }
  this.startWatching = () => {
    // chrome.tabs.get(this.id, (tabs) => {
    //   console.log("query", tabs)
    // }
    // )
    // this.timer = setTimeout(this.startWatching, 200)
  }
  // this.timer = setTimeout(this.startWatching, 200)

  this.request('create')
}
const TabWatcher = {
  tabs: [],
  init: () => {
    chrome.tabs.onCreated.addListener(
      (tabs) => {
        const tabItem = new TabItem(tabs.id, tabs.pendingUrl, tabs.favIconUrl)
        TabWatcher.tabs.push(tabItem)
        console.log('tabs', tabs)
      },
    )

    chrome.tabs.onRemoved.addListener(
      (tabId) => {
        const tabItem = TabWatcher.tabs.find((tabItem) => tabItem.id == tabId)
        TabWatcher.tabs = TabWatcher.tabs.filter((tabItem) => tabItem.id == tabId)
        if (tabItem) {
          tabItem.dispose()
        }
      },
    )

    chrome.tabs.onUpdated.addListener(
      (tabId) => {
        const tabItem = TabWatcher.tabs.find((tabItem) => tabItem.id == tabId)
        tabItem && tabItem.update()
      },
    )


    // chrome.tabs.onDetached.addListener(
    //   ({ tabId }) => {
    //     console.log('onDetached', tabId)

    //     const tabItem = TabWatcher.tabs.find((tabItem) => tabItem.id == tabId)
    //     tabItem && tabItem.hide()
    //   },
    // )


    // chrome.tabs.onActivated.addListener(
    //   ({ tabId }) => {
    //     console.log('onActivated', tabId)
    //     TabWatcher.tabs.map(tabItem => {
    //       if(tabItem.id == tabId) {
    //         tabItem.show()
    //       } else {
    //         tabItem.hide()
    //       }
    //     })
    //     const tabItem = TabWatcher.tabs.find((tabItem) => tabItem.id == tabId)
    //     tabItem && tabItem.show()
    //   },
    // )

  }
}

TabWatcher.init()